import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import * as auth from '@/utils/auth'
import request from '@/utils/request'
import { PUBLIC_API, READER_API } from '@/utils/api'

const user = ref(null)

export function useAuth() {
    const router = useRouter()

    const isAuthenticated = computed(() => !!auth.getToken())

    const handleAuthError = () => {
        console.error("Authentication error or failed to fetch user. Clearing session.");
        auth.removeToken();
        auth.removeUserRole();
        user.value = null;
        router.push('/login');
    }

    const fetchUser = async () => {
        if (auth.getToken()) {
            console.log("Token found, fetching user profile...");
            try {
                const res = await request.get(`${READER_API}/profile`);
                console.log("User profile fetched:", res);
                user.value = res;
            } catch (error) {
                console.error('Failed to fetch user:', error);
                handleAuthError();
            }
        } else {
            console.log("No token found, skipping user fetch.");
        }
    }

    const login = async (credentials) => {
        try {
            console.log("Attempting to log in with:", credentials);
            const response = await request.post(`${PUBLIC_API}/login`, credentials)
            const { token } = response;
            console.log("Login successful, received token:", token);
            auth.setToken(token)
            await fetchUser();
            if (user.value) {
                console.log("User object available:", user.value);
                console.log("Setting user role:", user.value.role);
                auth.setUserRole(user.value.role);

                console.log("Redirecting to home page...");
                router.push('/')
            } else {
                console.error("Login succeeded but failed to fetch user profile afterwards.");
            }
        } catch (error) {
            console.error('Login failed:', error)
            throw error
        }
    }

    const logout = () => {
        console.log("Logging out.");
        auth.removeToken()
        auth.removeUserRole()
        user.value = null
        router.push('/login').then(() => {
            window.location.reload()
        })
    }

    // 初始化时尝试获取用户信息
    if (!user.value) {
        fetchUser();
    }

    return {
        isAuthenticated,
        user,
        login,
        logout,
        fetchUser
    }
}